<template>
  <div v-if="is_info">{{value}}</div>
  <div v-else class="form_item-position">
    <input type="hidden" :name="name" :value="value">
    <el-input :model-value="value" :size="size" @input="$emit('update:value', $event)" @change="$emit('change', $event)" placeholder="格式：经度,纬度" clearable>
      <template #append>
        <el-button @click="open">选择位置</el-button>
      </template>
    </el-input>
    <el-dialog v-model="map_show" width="80%" :draggable="true" style="" top="5vh">
      <div ref="map" style="width: 100%;height: 65vh;position: relative;"></div>
      <template #header>
        <el-input v-model="address" placeholder="输入检索地址" @keyup.enter="search_address" style="width: 300px;">
          <template #append>
            <el-button @click="search_address">搜索</el-button>
          </template>
        </el-input>
      </template>
      <template #footer >
        <div class="flex" style="justify-content: flex-end">
          <el-button @click="update_value">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import s94Mjs from "s94-js";
import S94Mjs from "s94-js";

var map_data = {};
export default {
  _title_: '位置',
  _can_form_param_: true,
  name: "position",
  props: ['name', 'value', 'config', 'is_info', 'size', 'is_list'],
  emits: ['update:value', 'change'],
  data(){
    return {
      need_display: true,
      this_value: this.value,
      map_status: false,
      map_show: false,
      address: '',
    }
  },
  methods: {
    update_value(v){
      if (!map_data.latLng) return;
      v = map_data.latLng.lng+','+map_data.latLng.lat;
      this.need_display = false;
      setTimeout(()=>{this.need_display = true;},5);
      this.$emit('update:value', v);
      this.$emit('change', v);
      this.map_show = false;
    },

    init_map(){
      let app = this;
      map_data.latLng = new TMap.LatLng(35.76952494967395, 107.03757037136839);
      let dom = this.$refs['map'];
      if (!dom) return;
      let map = map_data.map = new TMap.Map(this.$refs['map'], {
        zoom: 12,
        center: map_data.latLng,
        draggableCursor: 'default',
        draggingCursor: 'default',
      });
      map_data.marker = new TMap.MultiMarker({
        map: map,
        geometries: []
      });
      map.on('click',function (e){
        app.update_position(e.latLng);
      })
      map_data.geocoder = new TMap.service.Geocoder();
      this.map_status = true;
    },
    update_position(latLng){
      map_data.latLng = latLng || map_data.latLng;
      map_data.marker.updateGeometries([
        {
          "id": "min",
          "position": map_data.latLng,  //点标记坐标位置
        }
      ]);
    },
    search_address(){
      let addr = this.address ? this.address.replace(/\s/g,'') : '';
      if (!addr) return this.$message('地址不能为空');
      map_data.geocoder.getLocation({ address: this.address }).then((result) => {
        let latLng = result.result.location;
        this.update_position(latLng);
        map_data.map.setCenter(latLng);
        if (map_data.map.getZoom() < 12){
          map_data.map.setZoom(12);
        }
      });
    },
    load_js(src, callback){
      let setup = {src}
      let cache_list = {};
      let callback_promise;
      document.querySelectorAll('script[src]').forEach(dom=>{
        var k = S94Mjs.url(dom.src);
        if(!cache_list[k]) cache_list[k] = this;
      });
      let srcs = [src];
      var length = srcs.length;
      var scriptNodes=[];
      function callback_action(){
        if (--length > 0) return;
        typeof(callback)=="function" && callback.call(scriptNodes, scriptNodes);
        callback_promise(scriptNodes);
      }
      for (var i = 0; i < srcs.length; i++) {
        var k = S94Mjs.url(srcs[i]);
        var row = cache_list[k];
        if (row && !setup.refresh){
          row.loading ? row.loadCallbacks.push(callback_action) : callback_action();
        }else{
          row = document.createElement("script");
          row.type = setup.type || '';
          row.loading = true;
          row.loadCallbacks=[callback_action];
          row.onload = function() {
            // callback_load.call(this, this);
            delete this.loading;
            for (; 0 < this.loadCallbacks.length;) {
              this.loadCallbacks[0]();
              this.loadCallbacks.splice(0,1);
            }
          }
          row.onerror = function(e){
            // callback_error.call(this, this);
            delete this.loading;
            parent.removeChild(row);
          }
          row.src = srcs[i];
          parent.appendChild(row);
        }
        scriptNodes.push(row);
        cache_list[k] = row;
      }
      return new Promise(function (resolve){callback_promise=resolve;});
    },
    open(){
      this.map_show = true;
      if (!this.map_status) {
        let map_ready = new Promise(function (next){setTimeout(next, 500)})
        this.load_js('https://map.qq.com/api/gljs?v=1.exp&key=LQ6BZ-4O6RN-7FZFF-S3PRB-EL5U3-OZBH3&libraries=service', ()=>{
          map_ready.then(()=>{ this.init_map();this.open(); })
        })
        return;
      }
      let value_arr = this.value ? this.value.split(',') : [];
      if (value_arr.length==2){
        map_data.latLng = new TMap.LatLng(value_arr[1], value_arr[0]);
        map_data.map.setCenter(map_data.latLng);
        this.update_position();
      }
    },
  },
  watch: {
  },
  computed: {
  },
  mounted() {}
}
</script>

<style scoped>
.panel{position: absolute;font-size: 16px;background: #FFF;border-radius: 06px;width:300px;padding: 10px;z-index: 9;top: 50px;left: 20px;}
</style>